package cn.tedu.csmall.product.filter;

import cn.tedu.csmall.product.security.LoginPrincipal;
import cn.tedu.csmall.product.web.JsonResult;
import cn.tedu.csmall.product.web.ServiceCode;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * 解析JWT的过滤器
 *
 * 1、首先,清除SecurityContext中的认证信息
 * 2、如果客户端没有携带JWT，则放行，由后续的组件进行处理
 * 3、如果客户端携带了有效的JWT，则解析，并将解析结果用于创建认证对象，最终将认证对象存入SecurityContext中
 *
 * @author 寒暄
 * @version 0.0.1
 */
@Slf4j
@Component
public class JwtAuthorizationFilter extends OncePerRequestFilter {

    public static final int JWT_MIN_LENGTH = 113;

    @Value("${csmall.jwt.secret-key}")
    private String secretKey;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        log.debug("处理JWT的过滤器开始执行...");

        // 清空Security上下文
        // Security上下文中的认证信息也会被清除
        // 避免前序携带JWT且解析成功后将认证信息存入Security上下文后，后续不携带JWT也能访问的“问题”
        SecurityContextHolder.clearContext();

        // 尝试从请求头中获取JWT数据
        String jwt = request.getHeader("Authorization");
        log.debug("尝试从请求头中获取JWT数据：{}", jwt);

        // 判断客户端是否携带了有效的JWT数据,如果没有,直接放行(由后面的Security处理)
        // StringUtils.hasText(),点进去后源码意义：文本内容不为null，不为空，包含有效字符为true
        if (!StringUtils.hasText(jwt) || jwt.length() < JWT_MIN_LENGTH) {
            log.debug("过滤器执行【放行】");
            filterChain.doFilter(request, response);
            return;
        }

        // 程序执行到此处，表示客户端携带了有效的JWT，则尝试解析
        log.debug("获取到的JWT被视为【有效】，尝试解析...");
        response.setContentType("application/json; charset=utf-8");
//        String secretKey = "asd2as352da3sdAA!@sad8aF..FS2!AA";
        Claims claims;
        try {
            claims = Jwts.parser()
                    .setSigningKey(secretKey)
                    .parseClaimsJws(jwt)
                    .getBody();
        } catch (ExpiredJwtException e) {
            log.debug("解析JWT时出现ExExpiredJwtException");
            String message = "登录信息已过期，请重新登录！";
            ServiceCode serviceCode = ServiceCode.ERR_JWT_EXPIRED;
            JsonResult<Void> jsonResult = JsonResult.fail(serviceCode.getValue(), message);
            String jsonResultString = JSON.toJSONString(jsonResult);
            PrintWriter writer = response.getWriter();
            writer.println(jsonResultString);
            return;
        } catch (MalformedJwtException e) {
            log.debug("解析JWT时出现MalformedJwtException");
            String message = "非法访问!";
            ServiceCode serviceCode = ServiceCode.ERR_JWT_MALFORMED;
            JsonResult<Void> jsonResult = JsonResult.fail(serviceCode.getValue(), message);
            String jsonResultString = JSON.toJSONString(jsonResult);
            PrintWriter writer = response.getWriter();
            writer.println(jsonResultString);
            return;
        } catch (SignatureException e) {
            log.debug("解析JWT时出现SignatureException");
            String message = "非法访问";
            ServiceCode serviceCode = ServiceCode.ERR_JWT_SIGNATURE;
            JsonResult<Void> jsonResult = JsonResult.fail(serviceCode.getValue(), message);
            String jsonResultString = JSON.toJSONString(jsonResult);
            response.setContentType("application/json; charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.println(jsonResultString);
            return;
        } catch (Throwable e) {
            log.debug("解析JWT时出现Throwable,需要开发人员在JWT过滤器中补充对异常的处理");
            e.printStackTrace();
            String message = "你有异常没有处理，请根据服务器端控制台的信息，补充对此类异常的处理！！！";
            PrintWriter writer = response.getWriter();
            writer.println(message);
            return;
        }

        // 获取JWT中的管理员信息
        String username = claims.get("username", String.class);
        Long id = claims.get("id", Long.class);
        String authoritiesJsonString = claims.get("authoritiesJsonString", String.class);
        log.debug("从JWT中获取id：{}", id);
        log.debug("从JWT中获取username：{}", username);
        log.debug("从JWT中获取authoritiesJsonString：{}", authoritiesJsonString);

        // 准备权限，将封装到认证信息中
        List<SimpleGrantedAuthority> authorities
                = JSON.parseArray(authoritiesJsonString, SimpleGrantedAuthority.class);

        // 创建Authentication对象,准备存入到SecurityContext的认证信息
        LoginPrincipal loginPrincipal = new LoginPrincipal(id, username);
        Authentication authentication =
                new UsernamePasswordAuthenticationToken(loginPrincipal, null, authorities);

        // 将认证信息存入到SecurityContext中
        SecurityContext securityContext = SecurityContextHolder.getContext();
        securityContext.setAuthentication(authentication);

        log.debug("过滤器执行【放行】");
        filterChain.doFilter(request, response);
    }
}
